package com.btex.app.tools;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.view.View;
import android.view.ViewGroup;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Tools {

    private static final String TAG = "Tool";

    /**
     * 网页爬虫获取标题
     *
     * @param open_url
     * @return
     */
    public static String getTitle(String open_url) {
        try {
            URL url = new URL(open_url);
            URLConnection conn = url.openConnection(); // 获取链接对象
            BufferedReader bufIn = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            //<title>免费体验</title>
            String mailreg = "<title>.*</title>";
            Pattern p = Pattern.compile(mailreg);
            while ((line = bufIn.readLine()) != null) {
                Matcher m = p.matcher(line);
                if (m.find()) {
                    String title = m.group();
                    title = title.substring(7, title.lastIndexOf("<"));
                    LogUtil.e(TAG, "获取到网页标题：" + title + " ---url: " + url);
                    return title;
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取本应用的版本👌
     */
    public static String getVersion(Context cxt) {
        try {
            PackageManager manager = cxt.getPackageManager();
            PackageInfo info = manager.getPackageInfo(cxt.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 受否安装包
     *
     * @param paramContext
     * @param paramString
     * @return
     */
    public static boolean appIsAvilible(Context paramContext, String paramString) {
        List localList = paramContext.getPackageManager().getInstalledPackages(0);
        ArrayList localArrayList = new ArrayList();
        if (localList != null) ;
        for (int i = 0; ; i++) {
            if (i >= localList.size())
                return localArrayList.contains(paramString);
            localArrayList.add(((PackageInfo) localList.get(i)).packageName);
        }
    }

    /**
     * 判断服务是否在跑
     *
     * @param mContext
     * @param className
     * @return
     */
    public static boolean isServiceRunning(Context mContext, String className) {

        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager)
                mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList
                = activityManager.getRunningServices(30);

        if (!(serviceList.size() > 0)) {
            return false;
        }

        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    /**
     * 将毫秒转化成00:00的形式
     *
     * @return
     */
    public static String getTimeStr(int time) {
        //转化成秒
        if (time >= 1000)
            time = time / 1000;
        else
            time = 1;
        int hour = time / 3600;
        time = time - hour * 3600;
        int fenz = time / 60;
        time = time - fenz * 60;
        int miao = time;
        String hourStr = hour <= 0 ? "" : (hour < 10 ? ("0" + hour + ":") : (hour + ":"));
        String fenStr = fenz <= 0 ? "00:" : (fenz < 10 ? ("0" + fenz + ":") : (fenz + ":"));
        String miaoStr = miao <= 0 ? "00" : (miao < 10 ? "0" + miao : "" + miao);
//		LogUtil.v("xm", "将"+time+"转化为"+(hourStr+fenStr+miaoStr));
        return hourStr + fenStr + miaoStr;
    }


    public static String getTodayDateTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.getDefault());
        return format.format(new Date());
    }


    public static String dataOne(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss",
                Locale.CHINA);
        Date date;
        String times = null;
        try {
            date = sdr.parse(time);
            long l = date.getTime();
            String stf = String.valueOf(l);
            times = stf.substring(0, 10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return times;
    }


    public static String timedate(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("MM-dd HH:mm:ss");
        @SuppressWarnings("unused")
        long lcc = Long.valueOf(time);
        int i = Integer.parseInt(time);
        String times = sdr.format(new Date(i * 1000L));
        return times;

    }


    /**
     * 四舍五入.
     *
     * @param number  原数
     * @param decimal 保留几位小数
     * @return 四舍五入后的值
     */
    public static BigDecimal round(double number, int decimal) {
        return new BigDecimal(number).setScale(decimal, BigDecimal.ROUND_HALF_UP);
    }


    /**
     * 获取view的高度
     *
     * @param view
     * @return
     */
    public static int getViewHeight(View view) {
        measureView(view);
        return view.getMeasuredHeight();
    }


    /**
     * 测量view
     *
     * @param view
     */
    public static void measureView(View view) {
        ViewGroup.LayoutParams p = view.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }

        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = View.MeasureSpec.makeMeasureSpec(lpHeight, View.MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        }
        view.measure(childWidthSpec, childHeightSpec);
    }


}
